import React, {useEffect, useState} from 'react';
import {Card, Form, Input, message, Popconfirm, Space, Table, Tooltip, Typography} from "antd";
import {EditOutlined} from "@ant-design/icons";
import {reqGetArticleSort, reqUpdateArticleSort} from "../../../../api/backStage/backStageApi";


const EditableCell = ({editing, dataIndex, title, inputType, record, index, children, ...restProps}) => {
    return (
        <td {...restProps}>
            {editing ?
                (
                    <Form.Item
                        name={dataIndex}
                        style={{margin: 0}}
                        rules={[
                            {
                                required: true,
                                message: `请输入${title}!`,
                            },
                        ]}
                    >
                        <Input/>
                    </Form.Item>
                ) : (children)
            }
        </td>
    );
};

const ArticleSort = () => {
    const [form] = Form.useForm();
    const [data, setData] = useState([]);
    const [editingKey, setEditingKey] = useState('');

    useEffect(() => {
        const getSortData = async () => {
            const result = await reqGetArticleSort()
            setData(result.data)
        }
        getSortData()
    }, [])
    //获取分类数据


    const isEditing = (record) => record.id === editingKey;
    //编辑按钮
    const edit = async (record) => {
        console.log(record)
        form.setFieldsValue({
            ...record,
        });
        setEditingKey(record.id);
    };
    const cancel = () => {
        setEditingKey('');
    };
    //保存按钮
    const save = async (record) => {
        try {
            const row = await form.validateFields();
            const {sort} = row
            const newData = [...data];
            const index = newData.findIndex((item) => record.id === item.id);
            console.log(sort)
            if (index > -1) {
                const item = newData[index];
                newData.splice(index, 1, {
                    ...item,
                    ...row,
                });
                await reqUpdateArticleSort(
                    {id: record.id, oldSort: record.sort, newSort: sort})
                setData(newData);
                setEditingKey('');
                message.success('修改分类成功!')
            } else {
                newData.push(row);
                setData(newData);
                setEditingKey('');
            }
        } catch (errInfo) {
            message.error(errInfo)
        }
    };
    const columns = [
        {
            title: '文章分类名称',
            dataIndex: 'sort',
            editable: true,
            align: 'center',
            width: 100,
            render: text => <span style={{color: '#1677ff'}}>{text}</span>
        },
        {
            title: '收录文章数量',
            dataIndex: 'num',
            width: 100,
            editable: false,
            align: 'center',
        },
        {
            title: '操作',
            width: 20,
            align: 'center',
            dataIndex: 'handle',
            render: (_, record) => {
                const editable = isEditing(record);
                return editable ? (
                    <span>
            <Typography.Link
                onClick={() => save(record)}
                style={{marginRight: 8,}}
            >
              保存
            </Typography.Link>
            <Popconfirm title="确定要取消吗?" onConfirm={cancel}>
              <a href="serialize-javascript">取消</a>
            </Popconfirm>
          </span>
                ) : (
                    <Tooltip title="修改">
                        <Space>
                            <EditOutlined onClick={() => edit(record)}/>
                        </Space>
                    </Tooltip>
                );
            },
        },
    ];
    const mergedColumns = columns.map((col) => {
        if (!col.editable) {
            return col;
        }
        return {
            ...col,
            onCell: (record) => ({
                record,
                dataIndex: col.dataIndex,
                title: col.title,
                editing: isEditing(record),
            }),
        };
    });
    return (
        <div className="ArticleSort">
            <Card>
                <Form form={form} component={false}>
                    <Table
                        style={{width: "100%"}}
                        components={{body: {cell: EditableCell,}}}
                        bordered
                        dataSource={data}
                        columns={mergedColumns}
                        rowClassName="editable-row"
                        rowKey={record => record.id}
                    />
                </Form>
            </Card>
        </div>
    );
};

export default ArticleSort;